package com.cos.shop.dao.impl;

import com.cos.shop.dao.CartDao;
import com.cos.shop.entity.Cart;
import com.cos.shop.entity.vo.CartVo;
import com.cos.shop.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: CartDaoImpl
 * Author: saber
 * Date:2022/9/19 13:34
 */
public class CartDaoImpl implements CartDao {

    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    @Override
    public Cart findByUidAndPid(int uid, int pid) throws SQLException {
        return qr.query("select * from cart where uid = ? and pid = ?"
                ,new BeanHandler<>(Cart.class),uid,pid);
    }

    @Override
    public int addCart(Cart cart) throws SQLException {
        return qr.update("insert into cart values(default,?,?,?,?)",
                cart.getUid(),cart.getPid(),
                cart.getCcount(),cart.getCnum());
    }

    @Override
    public int updateCart(Cart cart) throws SQLException {
        return qr.update("update cart set ccount=? , cnum = ? where cid  = ? ",
                cart.getCcount(),cart.getCnum(),cart.getCid());
    }

    @Override
    public List<CartVo> getCartAll(int uid) throws SQLException {
        return qr.query("select * from cart c inner join product p on c.pid=p.pid where uid = ?",
                new BeanListHandler<>(CartVo.class),uid);
    }

    @Override
    public int deleteCart(int uid, int pid) throws SQLException {
        return qr.update("delete from cart where uid = ? and pid = ?",uid,pid);
    }

    @Override
    public int deleteCart(int uid) throws SQLException {
        return qr.update("delete from cart where uid = ?",uid);
    }
}
